package com.chat.dao.impl;

import static com.chat.enums.ChatExceptionEnum.DB_REQUEST_FAILED;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.dao.ChatAccountDao;
import com.chat.domain.ChatAccount;
import com.chat.exception.ChatException;
import com.chat.mapper.ChatAccountMapper;
import com.chat.utils.AccountGenerator;
import jakarta.annotation.Resource;
import java.util.Objects;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class ChatAccountDaoImpl implements ChatAccountDao {

    @Resource
    private ChatAccountMapper chatAccountMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void insertAccount(ChatAccount chatAccount) {
        if (chatAccountMapper.insert(chatAccount) <= 0) {
            throw new ChatException(DB_REQUEST_FAILED);
        }
    }

    @Override
    public Long registerToGenerateAnAccount() {
        ChatAccount chatAccount;
        Long account;
        do {
            account = Long.valueOf(AccountGenerator.generateAccount());
            chatAccount = chatAccountMapper.selectOne(
                    new LambdaQueryWrapper<ChatAccount>().eq(ChatAccount::getAccount, account));
        } while (Objects.isNull(chatAccount));
        return account;
    }

    @Override
    public void resetPasswordByEmail(String email, String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        password = bCryptPasswordEncoder.encode(password);
        int i = chatAccountMapper.resetPasswordByEmail(email, password);
        if (i <= 0) {
            throw new ChatException(DB_REQUEST_FAILED);
        }
        stringRedisTemplate.delete("reset-password");
    }

    @Override
    public ChatAccount getAccountByAccountOrEmail(String account) {
        LambdaQueryWrapper<ChatAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatAccount::getUsername, account).or().eq(ChatAccount::getEmail, account);
        return chatAccountMapper.selectOne(queryWrapper);
    }
}
